<template>
  <div style="display: flex; height: 100%; flex: 1;">
    <HierarchyList :pagination="pagination" :columns="columns" :load-data="loadData"
                   :export-label="exportLabel" :export-asset="exportUrls"
                   :import-label="importLabel" :import-asset="importUrls"
                   ref="refHiUrl" :search-form="searchItems" :create-label="addUrlLabel"
                   :add-item="addUrl"/>

    <EditDialog ref="refEditDlg" :columns="columns" :rules="rules" :submit="onSubmit"
                :form-label-width="100" :is-show-dialog="false"/>

    <ImportDataDialog ref="refImport" url="/uni-center/v1/excel/asset/import/type"
                      :tips="'是否更新已经存在的地址信息'" :do-upload="uploadAction" />
  </div>
</template>

<script setup lang="ts">

import {onMounted, reactive, ref, computed} from "vue";
import {buildAsset} from "@/utils/sop/DataUtil";
import {buildSearchForms} from "@/views/sop/data/PageData";
import {msgError, msgInfo} from "@/utils/InfoUtil";
import EditDialog from "@/components/common/EditDialog.vue";
import HierarchyList from "@/views/sop/list/HierarchyList.vue";
import {useCurrent} from "@/utils/sop/UseCurrentFunc";
import {currentNames, TYPES} from "@/stores/conf";
import {useAssetOp} from "@/utils/sop/UseAssetOp";
import {exportAssetByType, getStateOptions, getStateTag, getStateText, handleResult} from "@/utils/SystemUtil";
import {requestForm} from "@/apis/request";
import ImportDataDialog from "@/widget/ImportDataDialog.vue";
import {useStore} from "@/stores";
import {hasMenuPermit} from "@/utils/sop/PermitUtil";

const props = withDefaults(defineProps<{
  product?: boolean,
  entry: any,
}>(), {});

const store = useStore();
const refImport = ref();
const refHiUrl = ref();
const refEditDlg = ref();

const currentItem = ref();
const searchItems = ref(buildSearchForms('地址', props.product));

const {updateCurrent} = useCurrent(currentNames.URL);
const {doLoadAsset, doSaveAsset, doDeleteAsset} = useAssetOp(props.entry);

const rules = reactive({
  name: [{required: true, message: '请输入地址名称', trigger: ['blur']},],
  $urls: [{required: true, message: '请输入地址', trigger: ['blur']},],
})

const addUrlLabel = computed(() => {
  return hasMenuPermit('asset:url:add') ? '新增地址' : '';
})

const importLabel = computed(() => {
  return hasMenuPermit('asset:url:import') ? '导入' : '';
})

const exportLabel = computed(() => {
  return hasMenuPermit('asset:url:export') ? '导出' : '';
})

const getTargetId = () => {
  return '';
}

const importUrls = () => {
  refImport.value.handleImport();
}

const exportUrls = async (parentId: string='') => {
  const platform: any = store.getCurrentPlatform();

  await exportAssetByType({
    platformId: platform.id,
    assetType: TYPES.URL
  }, `${TYPES.URL}_${new Date().getTime()}.xlsx`, {});
}

const uploadAction = async (option: any, url: any, headers: any) => {
  const platform: any = store.getCurrentPlatform();
  let formData: any = new FormData();
  formData.append("file", option.file);
  formData.append("assetType", TYPES.URL);
  formData.append("platformId", platform.id);

  await requestForm({
    url: url,
    method: 'post',
    headers: headers,
    data: formData,
  });
  refresh();
}

const loadData = async (params: any) => {
  const result = await doLoadAsset(getTargetId(), TYPES.URL, params);

  if (result && result.code === 0) {
    msgInfo('加载地址信息成功!');
    handleResult(result.data, ['$comment','$urls', '$filterType']);
  } else {
    msgError(result ? result.message : '加载地址信息失败！');
  }

  return result;
}

const refresh = () => {
  refHiUrl.value?.refresh()
}

const onSubmit = async (item: Record<string, any>) => {
  let assetInfo = buildAsset(item, 'URL', {
    $urls: item.$urls,
    $filterType: item.$filterType,
    $comment: item.$comment,
  });

  const result = await doSaveAsset(getTargetId(), assetInfo);
  if (result && result.code === 0) {
    msgInfo('保存地址信息成功!');
    setTimeout(() => refresh(),300);
  } else {
    msgError(result ? result.message : '保存地址信息失败！');
  }

  return result;
}

const newUrl = () => {
  return {
    state: 1,
    type: TYPES.URL,
    $filterType: 1,
  };
}

const pagination = ref({
  current: 1,
  pageSize: 20,
  total: 0,
});

const columns = ref([
  {
    id: 'id',
    name: '标识',
    hideCol: true,
    show: false,
    canEdit: false,
  },
  {
    id: 'name',
    name: '地址名称',
    show: true,
    action: (data: any, row: any, index: number) => {
      updateCurrent({type: TYPES.URL, ...row})
    }
  },
  {
    id: '$urls',
    name: '地址信息',
    show: true,
  },
  {
    id: '$filterType',
    name: '类型',
    show: true,
    tag: 'true',
    type: 'select',
    tagType: (tag: number) => { return tag == 1 ? 'success' : 'danger'; },
    tagText: (tag: number) => { return tag == 1 ? '白名单' : '黑名单'; },
    options: [
      {
        value: 1,
        label: '白名单'
      },
      {
        value: 2,
        label: '黑名单'
      }
    ]
  },
  {
    id: 'state',
    name: '状态',
    show: true,
    tag: 'true',
    type: 'select',
    tagType: (tag: number) => { return getStateTag(tag); },
    tagText: (tag: number) => { return getStateText(tag); },
    options: getStateOptions()
  },
  {
    id: '$comment',
    name: '描述',
    show: true,
  },
  {
    id: 'createTime',
    name: '创建时间',
    show: true,
    canEdit: false,
  },
  {
    id: 'operation',
    name: '操作',
    show: true,
    hideCol: true,
    fixed: 'right',
    canEdit: false,
    operations: [
      {
        name: '编辑',
        iconType: 'primary',
        disabled: (row: any) => {
          return !hasMenuPermit('asset:url:edit');
        },
        callback: (data: any, row: any) => {
          currentItem.value = row;
          refEditDlg.value?.editUpdate('编辑地址', row);
        }
      },
      {
        type: 'confirm',
        name: '删除',
        disabled: (row: any) => {
          return !hasMenuPermit('asset:url:delete');
        },
        confirm: async (data: any, row: any) => {
          const result = await doDeleteAsset(getTargetId(), row);
          if (result.code === 0) {
            msgInfo('删除地址成功！');
            setTimeout(() => refresh(),300);
          } else {
            msgError(result.message ? result.message : '删除地址失败！');
          }
        }
      }
    ]
  }
]);

const addUrl = () => {
  currentItem.value = newUrl();
  refEditDlg.value?.editAdd('新增地址', currentItem.value);
}

onMounted(() => {

})

defineExpose({
  refresh,
})

</script>

<style scoped>
.el-form-item-class .el-form-item__label {
  font-size: 12px;
}

</style>
